package com.shrikanthravi.customnavigationdrawer2.utils;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.ability.fraction.FractionScheduler;

import java.util.ArrayList;
import java.util.Optional;

public class FractionChangeManager {
    private final FractionManager mFragmentManager;
    private final int mContainerViewId;
    private final ArrayList<Fraction> mFragments;

    public FractionChangeManager(FractionManager fm, int containerViewId, ArrayList<Fraction> fragments) {
        this.mFragmentManager = fm;
        this.mContainerViewId = containerViewId;
        this.mFragments = fragments;
        initFragments();
    }

    private void initFragments() {
        for (int i = 0; i < mFragments.size(); i++) {
            Optional<Fraction> fractionByTag = mFragmentManager.getFractionByTag(String.valueOf(i));
            if (fractionByTag.isPresent()) {
                mFragmentManager.startFractionScheduler().hide(mFragments.get(i)).submit();
            } else {
                mFragmentManager.startFractionScheduler().add(mContainerViewId, mFragments.get(i), String.valueOf(i)).hide(mFragments.get(i)).submit();
            }
        }
        setFragments(0);
    }


    /**
     * 界面切换控制
     *
     * @param index 当前的fragment
     */
    public void setFragments(int index) {
        for (int i = 0; i < mFragments.size(); i++) {
            FractionScheduler ft = mFragmentManager.startFractionScheduler();
            Fraction fragment = mFragments.get(i);
            if (i == index) {
                ft.show(fragment).submit();
            } else {
                ft.hide(fragment).submit();
            }
        }
    }
}